#include "RingQueue.hpp"
#include "Task.hpp"

std::string SlefName()
{
    char name[128];
    snprintf(name, sizeof(name), "thread[0x%x]", pthread_self());
    return name;
}

// 生产
void *ProducotRoutine(void *rq)
{
    // 把类型强制转换一下
    // RingQueue<int> *ringqueue = static_cast<RingQueue<int> *>(rq);
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while (true)
    {
        // sleep(3);
        // 生产活动
        // int data = rand() % 10 + 1;
        // ringqueue->Push(data);
        // std::cout << "生产完成,生产的数据是: " << data << std::endl;
        // sleep(3);
        //
        // 生产任务
        int x = rand() % 10;
        int y = rand() % 5;
        char op = oper[rand() % oper.size()];
        Task t(x, y, op, mymath);
        ringqueue->Push(t);
        // 输出提示
        std::cout << SlefName() << ", 生产者派发了一个任务：" << t.toTaskString() << std::endl;
        // sleep(1);
    }
}

// 消费
void *ConsumerRoutine(void *rq)
{
    // RingQueue<int> *ringqueue = static_cast<RingQueue<int> *>(rq);
    RingQueue<Task> *ringqueue = static_cast<RingQueue<Task> *>(rq);
    while (1)
    {
        // 消费活动
        // int data;
        // ringqueue->Pop(&data);
        // std::cout << "消费完成,消费的数据是: " << data << std::endl;
        // sleep(1);

        // 消费任务
        Task t;
        ringqueue->Pop(&t);
        std::string result = t();
        std::cout << SlefName() << ", 消费者消费了一个任务：" << result << std::endl;
        // sleep(1);
    }
}

int main()
{
    // 构建一个随机数
    srand((unsigned int)time(nullptr) ^ getpid() ^ pthread_self());

    // 创建一个环形队列对象
    // RingQueue<int> *rq = new RingQueue<int>();
    RingQueue<Task> *rq = new RingQueue<Task>();

    // 多生产，多消费的意义？？？
    pthread_t p[4], c[8];
    for (int i = 0; i < 4; i++)
        pthread_create(p + i, NULL, ProducotRoutine, (void *)rq);
    for (int i = 0; i < 8; i++)
        pthread_create(c + i, NULL, ConsumerRoutine, (void *)rq);

    // 释放线程
    for (int i = 0; i < 4; i++)
        pthread_join(p[i], NULL);
    for (int i = 0; i < 8; i++)
        pthread_join(c[i], NULL);

    // 释放内存
    delete rq;
    return 0;
}